/**
 * Created by FreezeSoul on 2017/7/22.
 */
'use strict';
define([
    "app/core/base",
    "app/core/util",
    "../commonMeta",
    "jquery",
    "underscore",
    'JSONParse',
    'loglevel'
], function (Chart, Util, Meta, $, _, JSON, log) {

    var property = {
        config: "property",
        option: [
            {
                group: '基础',
                id: 'TABLE_IS_BORDER',
                name: '显示边框',
                enable: true,
                type: 'checked',
                value: true,
                default: true,
                link: 'hasBorder',
                tooltip: '是否显示显示边框'
            },
            {
                group: '基础',
                id: 'TABLE_BORDER_COLOR',
                name: '边框颜色',
                enable: true,
                type: 'color',
                value: '#FFFFFF',
                default: '#FFFFFF',
                link: 'borderColor',
                tooltip: '边框颜色'
            },
            {
                group: '基础',
                id: 'TABLE_HEADER_ARRAY',
                name: '固定表头',
                enable: false,
                type: 'text',
                value: "",
                default: "",
                link: 'headerArray',
                tooltip: '固定表头，支持多行、合并，“,”分隔，“;”多行分隔，相同表头自动合并，<br/>如：合并表头1,合并表头1,合并表头1,合并表头2,合并表头2;日期,受理警情,有效警情,无效警情,有效警情比例'
            },
            {
                group: '基础',
                id: 'TABLE_HEADER_HEIGHT',
                name: '表头行高',
                enable: false,
                type: 'number',
                value: 30,
                default: 30,
                link: 'headerHeight',
                tooltip: '表头行高,只能统一设置'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_ROW_HEIGHT',
                name: '数据行行高',
                enable: false,
                type: 'number',
                value: 30,
                default: 30,
                link: 'dataRowHeight',
                tooltip: '数据行行高,只能统一设置'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_WIDTH',
                name: '表格列列宽',
                enable: false,
                type: 'text',
                value: "1",
                default: "1",
                link: 'dataColWidth',
                tooltip: '表格列列宽,占比设置，“,”分隔，确保数量为1或与列数匹配，否则无效，如：1,1,1,1 指的是均分'
            },
            {
                group: '基础',
                id: 'TABLE_HEADER_COLOR',
                name: '表头背景颜色',
                enable: false,
                type: 'text',
                value: "transparent",
                default: "transparent",
                link: 'headerColor',
                tooltip: '表头背景颜色，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_HEAD_FONT_COLOR',
                name: '表头字体颜色',
                enable: false,
                type: 'text',
                value: "transparent",
                default: "transparent",
                link: 'headerFontColor',
                tooltip: '表头字体颜色，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_HEAD_FONT_SIZE',
                name: '表头字体大小',
                enable: false,
                type: 'number',
                value: 24,
                default: 24,
                link: 'headerFontSize',
                tooltip: '表头字体大小'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_COLOR_I',
                name: '数据行背景颜色I',
                enable: false,
                type: 'text',
                value: "transparent",
                default: "transparent",
                link: 'dataRowColorI',
                tooltip: '数据行背景颜色I，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_COLOR_II',
                name: '数据行背景颜色II',
                enable: false,
                type: 'text',
                value: "transparent",
                default: "transparent",
                link: 'dataRowColorII',
                tooltip: '数据行背景颜色II，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_FONT_COLOR',
                name: '数据行字体颜色',
                enable: false,
                type: 'text',
                value: "transparent",
                default: "transparent",
                link: 'dataRowFontColor',
                tooltip: '数据行字体颜色，“,”分隔，确保数量为1或与列数匹配，否则无效，如：red,green,blue,yellow'
            },
            {
                group: '基础',
                id: 'TABLE_DATA_COL_FONT_SIZE',
                name: '数据行字体大小',
                enable: false,
                type: 'number',
                value: 24,
                default: 24,
                link: 'dataRowFontSize',
                tooltip: '数据行字体大小'
            },
            {
                group: '基础',
                id: 'TABLE_COLOR_SELECTOR',
                name: '颜色取色器',
                enable: true,
                type: 'color',
                value: '#FFFFFF',
                default: '#FFFFFF',
                tooltip: '颜色取色器，仅供其他颜色相关属性取色'
            },
            {
                group: '绑定',
                id: 'TABLE_BINDING',
                name: '数据绑定',
                enable: true,
                type: 'sortBinding',
                dataset: '',
                columns: [],
                tooltip: '表格数据绑定'
            }, {
                group: '绑定',
                id: 'FilterName',
                name: '过滤列名称',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterName',
                tooltip: '绑定数据集，客户端过滤字段列名称'
            },
            {
                group: '绑定',
                id: 'FilterValue',
                name: '过滤列默认值',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterValue',
                tooltip: '绑定数据集，客户端过滤字段默认值'
            }
        ].concat($.extend(true, [], Meta.commonProperties)),
        MapOption: function (option) {
            Util.linkOption(this.option, option);
        }
    };

    var table = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._element = null;
            this._lastdata = null;
            this._container = null;
            this._data = [];
            this._header = [];
            this._option = {
                Binding: [],
                Events: [],
                Extend: $.extend(true, {}, property),
                Option: {
                    uuid: '',
                    class: '',
                    display: true,
                    hasBorder: true,
                    borderColor: "#000000",
                    headerArray: "",
                    headerHeight: 30,
                    dataRowHeight: 30,
                    dataColWidth: "1",
                    headerColor: "transparent",
                    headerFontColor: "#000000",
                    headerFontSize: 24,
                    dataRowColorI: "transparent",
                    dataRowColorII: "transparent",
                    dataRowFontColor: "#000000",
                    dataRowFontSize: 24,
                    initScript: '',
                    disposeScript: ''
                }
            };
        },
        init: function (element) {
            try {
                this._container = element;
            } catch (e) {
                log.error(e);
            }
        },
        _render: function (option) {
            $(this._container).empty();
            var borderStr = option.hasBorder ? ("border: 2px solid " + option.borderColor + ";") : "";
            var tableHtml = '<div style="overflow-y: auto;width: 100%;overflow-x: hidden;height: 100%;"><table style="width:100%;height: 100%;' + borderStr + '">';
            var headerArrayList = [];
            var tableHeaderColCount = 0;
            if (this._header && this._header.length > 0) {
                headerArrayList = [this._header];
                tableHeaderColCount = this._header.length;
            } else {
                _.each($.trim(option.headerArray).split(";"), function (headerListStr) {
                    var headerList = $.trim(headerListStr).split(",");
                    headerArrayList.push(headerList);
                    tableHeaderColCount = headerList.length;
                });
            }
            var headerBgColors = $.trim(option.headerColor).split(',');
            var headerFontColors = $.trim(option.headerFontColor).split(',');
            var colWidthArray = $.trim(option.dataColWidth).split(',');
            var totalWidth = _.reduce(colWidthArray, function (memo, num) {
                return parseInt(memo) + parseInt(num);
            }, 0);
            var widthPercentArray = [];
            _.each(colWidthArray, function (colWidth) {
                widthPercentArray.push(Math.round(colWidth / totalWidth * 100) + "%");
            });
            _.each(headerArrayList, function (headerArray) {
                var colSpanNumber = 1;
                tableHtml += '<tr style="height:' + $.trim(option.headerHeight) + 'px;font-size: ' + $.trim(option.headerFontSize) + 'px;font-weight: bold;">';
                $.each(headerArray, function (i, headerName) {
                    var nextHeaderName = headerArray.length === (i + 1) ? "" : headerArray[i + 1];
                    if (nextHeaderName !== headerName) {
                        var bgColorStr = "";
                        if (headerBgColors.length === 1) {
                            bgColorStr = 'background-color:' + headerBgColors[0] + ";";
                        } else {
                            bgColorStr = headerBgColors.length === headerArray.length ? ('background-color:' + $.trim(headerBgColors[i]) + ';') : "";
                        }
                        var fontColorStr = "";
                        if (headerFontColors.length === 1) {
                            fontColorStr = 'color:' + headerFontColors[0] + ";";
                        } else {
                            fontColorStr = headerFontColors.length === headerArray.length ? ('color:' + $.trim(headerFontColors[i]) + ';') : "";
                        }
                        var widthPercent = "";
                        if (widthPercentArray.length === headerArray.length) {
                            widthPercent = "width:" + widthPercentArray[i] + ";"
                        }
                        var borderStr = option.hasBorder ? ("border: 1px solid " + option.borderColor + ";") : "";
                        tableHtml += '<th colspan="' + colSpanNumber + '" style="text-align: center;' + bgColorStr + fontColorStr + widthPercent + borderStr + '">' + headerName + '</th>';
                        colSpanNumber = 1;
                    } else {
                        colSpanNumber++;
                    }
                });
                tableHtml += '</tr>';
            });
            var rowBgColors = [];
            var rowBgColorsI = $.trim(option.dataRowColorI).split(',');
            var rowBgColorsII = $.trim(option.dataRowColorII).split(',');
            var rowFontColors = $.trim(option.dataRowFontColor).split(',');
            $.each(this._data, function (n, row) {
                tableHtml += '<tr style="height:' + $.trim(option.dataRowHeight) + 'px;font-size: ' + $.trim(option.dataRowHeight) + 'px;">';
                $.each(row, function (i, col) {
                    rowBgColors = n % 2 === 0 ? rowBgColorsI : rowBgColorsII
                    var bgColorStr = "";
                    if (rowBgColors.length === 1) {
                        bgColorStr = 'background-color:' + rowBgColors[0] + ";";
                    } else {
                        bgColorStr = rowBgColors.length === tableHeaderColCount ? ('background-color:' + $.trim(rowBgColors[i]) + ';') : "";
                    }
                    var fontColorStr = "";
                    if (rowFontColors.length === 1) {
                        fontColorStr = 'color:' + rowFontColors[0] + ";";
                    } else {
                        fontColorStr = rowFontColors.length === tableHeaderColCount ? ('color:' + $.trim(rowFontColors[i]) + ';') : "";
                    }
                    var borderStr = option.hasBorder ? ("border: 1px solid " + option.borderColor + ";") : "";
                    tableHtml += '<td style="text-align: center;' + bgColorStr + fontColorStr + borderStr + '">' + $('<div/>').html(col).text() + '</td>';
                });
                tableHtml += '</tr>';
            });
            tableHtml += "</table></div>";
            var $table = $(tableHtml);
            $table.appendTo($(this._container));

            //Util.setCommonMeta(this, this._container, this._option.Option);
            //Util.initChartLifeTime(this, this._container, this._option.Option);

            return $table;
        },
        example: function () {
            try {
                var exampleOption = $.extend(true, {}, this._option.Option);
                exampleOption.headerArray = "合并表头1,合并表头1,合并表头1,合并表头2,合并表头2;日期,受理警情,有效警情,无效警情,有效警情比例";
                exampleOption.dataColWidth = "1,2,2,2,4";
                this._data = [["21", "164", "104", "57", "65.03%"], ["21", "164", "104", "57", "65.03%"], ["21", "164", "104", "57", "65.03%"], ["21", "164", "104", "57", "65.03%"], ["21", "164", "104", "57", "65.03%"], ["21", "164", "104", "57", "65.03%"], ["21", "164", "104", "57", "65.03%"]];
                this._element = this._render(exampleOption);
            } catch (e) {
                log.error(e);
            }
        },
        _bindEvent: function () {
            var _this = this;
            if (!this._filterDataHandle) {
                this._filterDataHandle = function (params) {
                    _this.filterDataHandle.call(_this, params);
                };
            }
            this._layout.removeListener("filterData", this._filterDataHandle);
            this._layout.addListener("filterData", this._filterDataHandle);
        },
        filterDataHandle: function (params) {
            var _this = this;
            var flag = false;
            var filterColumn = _.findWhere(this._option.Extend.option, {name: '过滤列名称'});
            var filterValue = _.findWhere(this._option.Extend.option, {name: '过滤列默认值'});

            if (filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                for (var prop in params) {
                    if (!params.hasOwnProperty(prop)) continue;
                    if (filterColumn.value === prop) {
                        filterValue.value = params[prop];
                        flag = true;
                    }
                }
            }
            if (flag && _this._lastdata) {
                _this.setData(_this._lastdata);
            }
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                Util.deepMapOption(property, this._option.Extend, this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        _filterTable: function (option, table) {
            var filterColumn = _.findWhere(option, {name: '过滤列名称'});
            var filterValue = _.findWhere(option, {name: '过滤列默认值'});

            if (table && filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                var tableCopy = _.map(table, _.clone);
                return _.filter(tableCopy, function (row) {
                    return row[filterColumn.value] === filterValue.value;
                });
            }
            return table;
        },
        _bindData: function (data) {
            var bindProperty = _.findWhere(this._option.Extend.option, {type: 'sortBinding'});
            if (!bindProperty) return;

            var dataSetCode = bindProperty.dataset;
            var columns = bindProperty.columns;
            var table = data[dataSetCode];
            var tableData = [];
            var tableHeader = [];
            _.each(columns, function (binding) {
                tableHeader.push(binding.ColumnName);
            });
            table = this._filterTable(this._option.Extend.option, table);
            if (table && table.length > 0) {
                $.each(table, function (j, row) {
                    var rowData = [];
                    _.each(columns, function (binding) {
                        rowData.push(row[binding.ColumnName]);
                    });
                    tableData.push(rowData);
                });
            }
            var tableHeaderProperty = _.findWhere(this._option.Extend.option, {id: 'TABLE_HEADER_ARRAY'});
            if (tableHeaderProperty.enable === false) {
                this._header = tableHeader;
            } else {
                this._header = [];
            }
            this._data = tableData;
        },
        setData: function (data) {
            try {
                this._lastdata = data;
                this._readProperty();
                //data = Util.parseDataChartLifTime(this, this._container, this._option.Option, data);
                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                ) {
                    this._bindData(data);
                    this._readProperty();
                }
                if (this._data.length > 0)
                    this._element = this._render(this._option.Option);

                this._bindEvent();
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            return this._option;
        },
        setTheme: function (theme) {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                $(this._element).remove();
                this._layout.removeListener("filterData", this._filterDataHandle);
                //Util.disposeChartLifeTime(this, this._container, this._option.Option);

            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return this._element;
        },
        getChart: function () {
            return this._element;
        }
    });

    return {
        Chart: table,
        Property: property
    };
});